package com.example.datn.activities;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.example.datn.R;
import com.example.datn.adapter.SongItemInAlbumAdapter;
import com.example.datn.manager.AlbumManager;
import com.example.datn.manager.SongManager;
import com.example.datn.objects.AlbumObject;
import com.example.datn.objects.SongObject;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class PlayAlbumMediaActivity extends Activity implements OnClickListener, OnCompletionListener{

	private TextView tv_albumName, tv_luotNghe, tv_luotThich, tv_timer, tv_current_song_playMedia, tv_album_infor;
	private SeekBar sb_songTimeProgress;
	private ImageButton btn_play_pause, btn_replay, btn_previousSong, btn_nextSong, btn_likeSong, btn_shareSong;
    private final Handler handler = new Handler();
    private MediaPlayer mediaPlayer;
    private AlbumObject album;
    private SongObject song;
    private ImageView iconAlbum;
    private ListView lv_listSongOfAlbum;
    private ArrayList<SongObject> listSongOfAlbum;
    SongItemInAlbumAdapter adapter = null;
    boolean isLoadingSong = false;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.play_album_media_screen);
		initViews();
		
		album = AlbumManager.getInstance().getCurrentAlbum();
		if(album != null){
			tv_albumName.setText("Album: "+album.albumName);
			tv_luotNghe.setText(""+album.soLuotNghe);
			
			if(album.getBitmapImage() != null)
				iconAlbum.setImageBitmap(album.getBitmapImage());
			
			AlbumManager.getInstance().initListSong(album.albumId);
			listSongOfAlbum = AlbumManager.getInstance().getListSongOfAlbum();
			adapter = new SongItemInAlbumAdapter(this, R.layout.my_song_item_in_album, listSongOfAlbum);
			lv_listSongOfAlbum.setAdapter(adapter);
			lv_listSongOfAlbum.setOnItemClickListener(listItemClick);
			
			if(listSongOfAlbum.size() > 0)
				playSongOfAlbum(AlbumManager.getInstance().getCurrentSong());
			
			tv_album_infor.setMovementMethod(new ScrollingMovementMethod());
			if(album.albumDetail != null)
				tv_album_infor.setText(album.albumDetail);
			else if(album.linkPlayAlbum != null)
				new getAlbumInforTask().execute(album.linkPlayAlbum);
				
		}
	}
	
	//chay bai hat trong album
	private void playSongOfAlbum(SongObject song) {		
		try{
			if(song.linkAudio == null || song.linkAudio == "")
				new getLinkAudioTask().execute(song);
			else 
				playMedia(song.linkAudio);
				//new LoadMediaTask().execute(song);
		}
		catch(Exception e){e.printStackTrace();}
	}

	//khoi tao cac thanh phan cua trang
	private void initViews() {
		tv_albumName = (TextView)findViewById(R.id.albumName_playAlbum);
		tv_luotNghe  = (TextView)findViewById(R.id.luotNghe_playAlbum);
		tv_luotThich = (TextView)findViewById(R.id.luotThich_playAlbum);
		tv_current_song_playMedia = (TextView)findViewById(R.id.current_song_playAlbum);
		tv_timer 	 = (TextView)this.findViewById(R.id.tv_timer_playMedia);
		sb_songTimeProgress = (SeekBar)findViewById(R.id.seekbar_song_timeProgress);	
		lv_listSongOfAlbum = (ListView)findViewById(R.id.list_song_of_album);
		iconAlbum = (ImageView)findViewById(R.id.icon_album_playAlbum);
		tv_album_infor = (TextView)findViewById(R.id.tv_album_infor);
		
		btn_play_pause = (ImageButton)findViewById(R.id.ibtn_play_pause_playMedia);	
		btn_play_pause.setImageResource(R.drawable.ic_action_play1);
		btn_play_pause.setOnClickListener(this);
		btn_likeSong =(ImageButton)findViewById(R.id.ibtn_like_playMedia);
		btn_likeSong.setOnClickListener(this);
		btn_nextSong = (ImageButton)findViewById(R.id.ibtn_next_displayMedia);
		btn_nextSong.setOnClickListener(this);
		btn_previousSong = (ImageButton)findViewById(R.id.ibtn_previous_displayMedia);
		btn_previousSong.setOnClickListener(this);
		btn_replay = (ImageButton)findViewById(R.id.ibtn_replay_displayMedia);
		btn_replay.setOnClickListener(this);
		btn_shareSong = (ImageButton)findViewById(R.id.ibtn_share_playMedia);
		btn_shareSong.setOnClickListener(this);			
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ibtn_play_pause_playMedia:
			if(mediaPlayer != null){
				if(mediaPlayer.isPlaying()){
					mediaPlayer.pause();
					btn_play_pause.setImageResource(R.drawable.ic_action_play1);
				}
				else{
					mediaPlayer.start();
					btn_play_pause.setImageResource(R.drawable.ic_action_pause1);
				}
			}
			break;
		
		case R.id.ibtn_next_displayMedia: //next bai hat tiep theo trong album
			if(mediaPlayer.isPlaying())
				mediaPlayer.stop();
			song = AlbumManager.getInstance().getNextSongOfAlbum();
			playSongOfAlbum(song);
			break;
			
		case R.id.ibtn_previous_displayMedia:  //quay lai bai hat trc trong album
			if(mediaPlayer.isPlaying())
				mediaPlayer.stop();
			song = AlbumManager.getInstance().getPreviousSongOfAlbum();
			playSongOfAlbum(song);
			break;
		}
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		song = AlbumManager.getInstance().getNextSongOfAlbum();
		playSongOfAlbum(song);
	}
	
	//bat su kien click vao bai ha trong list
	OnItemClickListener listItemClick = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int id,
				long arg3) {
			if(!isLoadingSong){
				if(mediaPlayer !=null && mediaPlayer.isPlaying())
					mediaPlayer.reset();
				song = listSongOfAlbum.get(id);	
				SongManager.getInstance().setCurrentSong(song);
				if(song.linkAudio == null || song.linkAudio == "")
					new getLinkAudioTask().execute(song);
				else 
					playMedia(song.linkAudio);
			}
		}
	};
	
	@Override
	public void onBackPressed() {		
		super.onBackPressed();		
		killMediaPlayer();
	}

	//asynctask de load link audio
    private class getLinkAudioTask extends AsyncTask<SongObject, Void, Void>{
    	SongObject song;
    	String link = "";
    	
    	@Override
		protected void onPreExecute() {    		
    		isLoadingSong = true;
			tv_current_song_playMedia.setText("loading");
			btn_play_pause.setVisibility(View.INVISIBLE);
			btn_nextSong.setVisibility(View.INVISIBLE);
			btn_previousSong.setVisibility(View.INVISIBLE);
			btn_replay.setVisibility(View.INVISIBLE);
			super.onPreExecute();
		}
    	
		@Override
		protected Void doInBackground(SongObject... params) {			
			try {			
				Document doc;						
				song = params[0];
				doc = Jsoup.connect(song.urlSong).get();				
				String a = doc.toString(),b;								
				Pattern pattern = Pattern.compile("xmlURL=([^&]*)");
				Matcher matcher = pattern.matcher(a);
				if (matcher.find()){
				    b = matcher.group(1);			    			   
				    doc = Jsoup.connect(b).get();				
					pattern = Pattern.compile("</source>(.+?)=");
					matcher = pattern.matcher(doc.toString());
					if (matcher.find()){
						link = matcher.group(1);
					}
				}				
			} catch (IOException e) {
				e.printStackTrace();
			}		
			
			song.linkAudio = link;
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {			
			super.onPostExecute(result);			
			if(song.linkAudio != "")
				playMedia(song.linkAudio);
		}    			
    }
	
	//chay seekbar
	private void primarySeekBarProgressUpdater() {
    	try{
    		int time = mediaPlayer.getCurrentPosition()/1000;
    		//hien thi dong ho thoi gian chay nhac
    		tv_timer.setText(SongManager.convertTime(time) + " | " + 
    					SongManager.convertTime(mediaPlayer.getDuration()/1000));    		
    		sb_songTimeProgress.setProgress(time);
        	
        	if(mediaPlayer.isPlaying()){
        		Runnable notification = new Runnable() {				
    				@Override
    				public void run() {
    					primarySeekBarProgressUpdater();
    				}
    			};
    			handler.postDelayed(notification,1000);
        	}
    	}catch(Exception e){
    		Log.d("loi", " --- " + e.toString());
    		killMediaPlayer();
    	}
    }
	    
	//giai phong mediaplayer
	private void killMediaPlayer() {
        if(mediaPlayer!=null) {
            try {
            	mediaPlayer.reset();
                mediaPlayer.release();
                SongManager.getInstance().setCurrentMediaPlayer(null);
            }
            catch(Exception e) {
                e.printStackTrace();
            }
        }
    }
	
	//chay audio tu url 
	private void playMedia(String url){
		tv_current_song_playMedia.setText("loading");
		isLoadingSong = true;
		btn_play_pause.setVisibility(View.INVISIBLE);
		btn_nextSong.setVisibility(View.INVISIBLE);
		btn_previousSong.setVisibility(View.INVISIBLE);
		btn_replay.setVisibility(View.INVISIBLE);
		
		//killMediaPlayer();
		if(mediaPlayer == null)
			mediaPlayer = new MediaPlayer();	
		else if(mediaPlayer.isPlaying()){
			mediaPlayer.stop();			
		}
		mediaPlayer.reset();
        try {
			mediaPlayer.setDataSource(url);
			mediaPlayer.prepare();
		} catch (Exception e) {
			e.printStackTrace();
		} 			
        
        mediaPlayer.start();					
		mediaPlayer.setOnCompletionListener(PlayAlbumMediaActivity.this);
		SongManager.getInstance().setCurrentMediaPlayer(mediaPlayer);	
		refresh();
		isLoadingSong = false;
		
	}

	private void refresh() {
		if(song == null)
			song = AlbumManager.getInstance().getCurrentSong();
		tv_current_song_playMedia.setText("Bài hát: " + song.songName);
		btn_play_pause.setVisibility(View.VISIBLE);
		btn_play_pause.setImageResource(R.drawable.ic_action_pause1);
		btn_nextSong.setVisibility(View.VISIBLE);
		btn_previousSong.setVisibility(View.VISIBLE);
		btn_replay.setVisibility(View.VISIBLE);													
		sb_songTimeProgress.setMax(mediaPlayer.getDuration()/1000);				
		//SongManager.getInstance().setCurrentMediaPlayer(mediaPlayer);				
		//khoi tao bo dem thoi gian
		primarySeekBarProgressUpdater();
	}
	
	private class getAlbumInforTask extends AsyncTask<String, Void, Void>{
		String text = "";
		
		@Override
		protected Void doInBackground(String... params) {
			try {			
				Document doc;
				doc = Jsoup.connect(params[0]).get();
				Elements divs = doc.select("div");
				for (Element div : divs) {	 
					if(div.hasClass("album-info")){
						Elements infors = div.select("p");
						for(Element infor : infors){
							if(infor.hasClass("rows2"))
								text = infor.text();
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			tv_album_infor.setText(text);
			super.onPostExecute(result);
		}
				
	}
}
